import Vue from "vue";

import * as sgApi from "@teld/api-proxy/src/utils/ajax.js";
import * as common from "@teld/api-proxy/src/utils/common.js";
import * as cookie from "@teld/api-proxy/src/utils/cookie.js";
import * as gaode from "@teld/api-proxy/src/utils/gaode.js";
import * as storage from "@teld/api-proxy/src/utils/storage.js";
import * as url from "@teld/api-proxy/src/utils/url.js";
import * as environment from "@teld/api-proxy/src/utils/environment.js";
import * as application from "@teld/api-proxy/src/utils/application.js";

import { init } from "@/api";
init(sgApi, cookie, common, gaode, storage, url, environment, application);

const utils = {
  sgApi,
  cookie,
  common,
  gaode,
  storage,
  url,
  environment,
  application,
};
const plugin = {
  install(Vue) {
    Vue.prototype.$utils = utils;
    Vue.utils = utils;
  },
  $utils: utils,
};

Vue.use(plugin);

Date.prototype.format = function(fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};


function getMainDomain() {
  var hostname = window.location.hostname;
  var parts = hostname.split('.').reverse();
  if (parts != null && parts.length > 1) {
    var mainDomain = parts[1] + '.' + parts[0];
    
    // 检查是否是国家代码顶级域名 (ccTLD) 如 .co.uk, .com.cn 等
    if (parts.length > 2 && parts[2].length == 2) {
      mainDomain = parts[2] + '.' + mainDomain;
    }
    return mainDomain;
  }
}

// 在这里可以自己调整SG地址
window.cuntomNginxSG = function() {
  let hostname = window.location.hostname;

  if (hostname.includes("teld.cn")) {
    return "//sgi.teld.cn";
  } else if (hostname.includes("teld.org")) {
    return "//sgi.teld.org:9080";
  } else if (hostname.includes("teld5.top")) {
    return "//sgi.teld5.top";
  } else if (hostname.includes("teld9.top")) {
    return "//sgi.teld9.top";
  } else if (hostname.includes("wyqcd.com")) {
    return "//sgi.wyqcd.com:7777";
  }else if (hostname.includes("teld1.xyz")) {
    return "//sgi.teld1.xyz";
  }

  return `//sgi.${getMainDomain()}`;
};

window.addEventListener("unhandledrejection", function(event) {
  event && event.preventDefault();
});
